---@class EntityHitSystem:Battle.EntityComponent
local EntityHitSystem = Battle.CreateClass("EntityHitSystem",Battle.EntityComponent)
Battle.EntityHitSystem = EntityHitSystem
function EntityHitSystem:OnCreate()
    self:Register()
    local global = Battle.GlobalConfig
    self.hitMaxCount = global.GetInt(22)    --受击次数
    self.damageHpPer = global.GetInt(23)/10000   --血量
    self.swingProbability = global.GetInt(24)/10000--概率
    self.hitInterval = global.GetInt(25)/1000    --间隔

    self.hitCount = 0
    self.hitTime = 0
    self:RegUpdate(true)
end
function EntityHitSystem:OnDestroy()
    self:UnRegister()
end
function EntityHitSystem:OnInitialized()

end
function EntityHitSystem:Register()
    local sys = self.actor.eventSystem
    sys:Register(Battle.Event.ActorHitAfter,self.Event_Hit,self)
    sys:Register(Battle.Event.SkillEnd,self.Event_SkillEnd,self)
    sys:Register(Battle.Event.SkillFrontSwingFinished,self.Event_FrontSwingFinished,self)

end
function EntityHitSystem:UnRegister()
    local sys = self.actor.eventSystem
    sys:UnRegister(Battle.Event.ActorHitAfter,self.Event_Hit,self)
    sys:UnRegister(Battle.Event.SkillEnd,self.Event_SkillEnd,self)
    sys:UnRegister(Battle.Event.SkillFrontSwingFinished,self.Event_FrontSwingFinished,self)

end
function EntityHitSystem:Update(dt)
    if self.hitTime > 0 then
        self.hitTime = self.hitTime - dt
    end
end

---@param args Battle.HitArgs
function EntityHitSystem:Event_Hit(args)
    if args.damageData.damage <= 0 then
        return
    end
    self.hitCount = self.hitCount + 1
    if self.hitTime > 0 then
        return
    end
    if self.hitCount >= self.hitMaxCount then
        if self:HandleHit() then
            self.hitCount = 0
        end
        return
    end
    if args.damageData.damage/self.actor:GetHpMax() > self.damageHpPer then
        self:HandleHit()
        return
    end
    if self.isSwing and math.random() <= self.swingProbability then
        self:HandleHit()
        return
    end
end
function EntityHitSystem:HandleHit()
    if self.actor:IsDead() then return false end
    if self.actor.effectStateSystem:HasState(Battle.FighterStateEnum.IMMUNITY_HIT_INTERRUPT) then
        return false
    end
    self.hitTime = self.hitInterval
    self.actor.aiSystem:SetBlackboardValue("hit",true)
    return true
    --self.actor:EnterState(Battle.ActionState.Hit,nil,true)
end


---@param args SkillArgs
function EntityHitSystem:Event_FrontSwingFinished(args)
    local skill = args.skill
    if skill.skillData.skillType == Battle.SkillType.Normal then
        self.isSwing = true
    end
end
---@param args SkillArgs
function EntityHitSystem:Event_SkillEnd(args)
    local skill = args.skill
    if skill.skillData.skillType == Battle.SkillType.Normal then
        self.isSwing = false
    end
end